#include <iostream>
#include <vector>
#include <thread>
#include <mutex>
#include <queue>
#include <condition_variable>
#include <memory>

// Event 类定义
class Event {
public:
    virtual void handle() = 0;  		// 虚函数，具体事件需要实现此方法
    virtual ~Event() {}
};

// 具体的事件类型
class ConcreteEvent : public Event {
public:
    void handle() override {
        std::cout << "Handling Concrete Event" << std::endl;
    }
};

// 线程安全的队列
template<typename T>
class ThreadSafeQueue {
private:
    std::mutex mutex;
    std::queue<T> queue;
    std::condition_variable cond_var;
    bool closed = false;

public:
    void push(T value) {
        std::lock_guard<std::mutex> lock(mutex);
        if (closed) throw std::runtime_error("Pushing to a closed queue");
        queue.push(std::move(value));
        cond_var.notify_one();
    }

    T pop() {
        std::unique_lock<std::mutex> lock(mutex);
        cond_var.wait(lock, [this] { return !queue.empty() || closed; });
        if (queue.empty()) return nullptr;
        T value = std::move(queue.front());
        queue.pop();
        return value;
    }

    void close() {
        std::lock_guard<std::mutex> lock(mutex);
        closed = true;
        cond_var.notify_all();
    }
};

// 观察者类
class Observer {
private:
    std::thread worker;
    ThreadSafeQueue<std::shared_ptr<Event>> eventQueue;
    bool running = true;

    void run() {
        while (running) {
            std::shared_ptr<Event> event = eventQueue.pop();
            if (!event) break;  		// 接收空指针作为终止信号
            event->handle();
        }
    }

public:
    Observer() {
        worker = std::thread(&Observer::run, this);
    }

    ~Observer() {
        running = false;
        eventQueue.close();  			// 关闭队列并推送终止信号
        if (worker.joinable()) {
            worker.join();
        }
    }

    void update(std::shared_ptr<Event> event) {
        eventQueue.push(event);
    }
};

// 主题类
class Subject {
private:
    std::vector<std::shared_ptr<Observer>> observers;

public:
    void attach(std::shared_ptr<Observer> observer) {
        observers.push_back(observer);
    }

    void notify(std::shared_ptr<Event> event) {
        for (auto& observer : observers) {
            observer->update(event);
        }
    }
};

// 主函数
int main() {
    Subject subject;
    auto observer1 = std::make_shared<Observer>();
    auto observer2 = std::make_shared<Observer>();

    subject.attach(observer1);
    subject.attach(observer2);

    // 发送事件
    std::shared_ptr<Event> event = std::make_shared<ConcreteEvent>();
    subject.notify(event);

    // 给一些处理时间
    std::this_thread::sleep_for(std::chrono::seconds(1));

    return 0;
}